import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { AlertController, NavController } from "@ionic/angular";

@Component({
  selector: "app-login",
  templateUrl: "./login.page.html",
  styleUrls: ["./login.page.scss"],
})
export class LoginPage implements OnInit {
  constructor(
    public router: NavController,
    private http: HttpClient,
    public alertC: AlertController,
    public route: ActivatedRoute
  ) {}

  res: Result;

  logIn(username: HTMLInputElement, password: HTMLInputElement) {
    if (
      username.value.length >= 2 &&
      username.value.length <= 9 &&
      password.value.length >= 6 &&
      password.value.length <= 12
    ) {
      let url = "http://xiaoshuogebed.applinzi.com/login";
      let body = `uname=${username.value}&upwd=${password.value}`;
      const httpOptions = {
        headers: new HttpHeaders({
          "Content-Type": "application/x-www-form-urlencoded",
        }),
      };
      this.http.post(url, body, httpOptions).subscribe((res: Result) => {
        let code = res.code;
        if (code == 0) {
          this.alertC
            .create({
              header: "很遗憾，登录失败！",
              message: "用户名或密码输入错误",
              buttons: ["确定"],
            })
            .then((res) => res.present());
        } else {
          window.localStorage.setItem("uname", username.value);
          window.location.replace("/tabs/tab1");
        }
      });
    } else {
      this.alertC
        .create({
          header: "提示",
          message: "用户名2~9位,密码6~12位",
          buttons: ["确定"],
        })
        .then((res) => res.present());
    }
  }
  ngOnInit() {}
}
interface Result {
  code: number;
  msg: string;
  results: result[];
}
interface result {
  img: string;
  uname: string;
  upwd: string;
}
